package com.yeskery.nut.http;

import com.yeskery.nut.core.MultipartFile;
import com.yeskery.nut.core.NutException;
import com.yeskery.nut.util.IOUtils;

import java.io.*;

/**
 * 用于封装Http协议中上传的二进制文件对象
 * @author sprout
 * 2019-03-15 09:41
 * @version 1.0
 *
 * @see com.yeskery.nut.core.MultipartFile
 */
public class BasicMultipartFile implements MultipartFile, Serializable, Cloneable {

	/** 文件名 */
	private final String fileName;

	/** 文件类型 */
	private final String contentType;

	/** 文件的字节数组 */
	private final byte[] data;

	/**
	 * 构建一个 {@link BasicCookie}
	 * @param fileName 文件名
	 * @param contentType 文件类型
	 * @param data 文件的字节数组
	 */
	public BasicMultipartFile(String fileName, String contentType, byte[] data) {
		this.fileName = fileName;
		this.contentType = contentType;
		this.data = data;
	}

	@Override
	public String getFileName() {
		return fileName;
	}

	@Override
	public String getContentType() {
		return contentType;
	}

	@Override
	public byte[] getData() {
		return data;
	}

	@Override
	public InputStream getInputStream() {
		return new ByteArrayInputStream(data);
	}

	@Override
	public void saveAsFile(File file) {
		try (FileOutputStream fos = new FileOutputStream(file)) {
			IOUtils.writeByteArray(fos, data);
		} catch (IOException e) {
			throw new NutException(e);
		}
	}

	@Override
	public BasicMultipartFile clone() {
		try {
			return (BasicMultipartFile) super.clone();
		} catch (CloneNotSupportedException e) {
			throw new NutException(e);
		}
	}
}
